package com.se.controller;

import cn.hutool.core.util.StrUtil;
import com.se.domain.dto.page.PageDTO;
import com.se.domain.request.param.ListUserActParam;
import com.se.domain.vo.ResultVO;
import com.se.domain.vo.UserActItemVO;
import com.se.domain.vo.UserActListVO;
import com.se.domain.vo.UserVO;
import com.se.enums.ResultCode;
import com.se.exception.ResultException;
import com.se.global.AuthHeaderRequestWrapper;
import com.se.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/must/user/id")
    public ResultVO<Long> getCurrentUserId(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId) throws ResultException {

        return ResultVO.ok(userId);
    }

    @PostMapping("/must/user/info")
    public ResultVO<UserVO> getCurrentUserInfo(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId) throws ResultException {

        return ResultVO.ok(userService.getUserInfo(userId));
    }

    @PostMapping("/need/user/info")
    public ResultVO<UserVO> getCurrentUserInfoNeed(
            @RequestHeader(value = AuthHeaderRequestWrapper.USER_ID_HEADER_NAME, required = false) Long userId)
            throws ResultException {
        if(userId == null){
            return ResultVO.ok(new UserVO());
        }
        return ResultVO.ok(userService.getUserInfo(userId));
    }


    @PostMapping("/must/user/act/list")
    public ResultVO<UserActListVO> listUserAct(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestBody ListUserActParam param
    ) throws ResultException {
        this.checkListUserActParam(param);

        List<UserActItemVO> voList = userService.listUserAct(param, userId);

        UserActListVO vo = new UserActListVO();
        vo.setList(voList);
        vo.setPage(new PageDTO(param.getPage().getPage(), voList.size()));

        return ResultVO.ok(vo);
    }

    private void checkListUserActParam(ListUserActParam param) throws ResultException {

        switch (param.getType()){
            case "publish", "apply" -> {}
            default -> {
                throw new ResultException(ResultCode.PARAM_INVALID.getCode(), "type参数错误");
            }
        }

        if(!StrUtil.isBlank(param.getSort())){
            switch (param.getSort()){
                case "start", "end" -> {}
                default -> {
                    throw new ResultException(ResultCode.PARAM_INVALID.getCode(), "sort参数错误");
                }
            }
        }

        if(param.getDesc() == null){
            param.setDesc(false);
        }
    }
}
